import axios from "axios"
import store from '@/store/index.js'
import router from "../router";
import { Message } from "element-ui";
axios.defaults.baseURL = '';
axios.defaults.timeout = 102000;
axios.interceptors.request.use(config => {
  // Do something before request is sent
  let token = localStorage.getItem("token") ? localStorage.getItem("token") : "";
  config.headers.Authorization = token;
  return config;
}, error => {
  // Do something with request error
  return Promise.reject(error);
});

axios.interceptors.response.use(response => {
  // console.log(response);
  // token失效拦截回登录
  if (response.data.code == -5 || response.data.code == -3) {
    localStorage.removeItem('token')
    localStorage.removeItem('user_id')
    router.replace({ path: '/login' })
    Message(response.data.msg)
  }
  // Do something before response is sent
  return response.data;
}, error => {
  // Do something with response error
  return Promise.reject(error);
});

//封装的get请求方法
//url:string 请求路径
//params:Object|string 请求参数
function get(url, params = {}) {
  return new Promise((res, rej) => {
    axios({
      method: 'get',
      url,
      headers: {
        'access-token': store.state.token,
        'user-id': store.state.user_id
      },
      params
    }).then(data => {
      res(data)
    }).catch(err => {
      rej(err)
    })
  })
}

function post(url, data = {}) {
  return new Promise((res, rej) => {
    axios({
      method: 'post',
      url,
      headers: {
        'access-token': store.state.token,
        'user-id': store.state.user_id
      },
      data
    }).then(data => {
      res(data)
    }).catch(err => {
      rej(err)
    })
  })
}

// 文件流导出
function exportPost(url, data = {}) {
  return new Promise((res, rej) => {
    axios({
      method: 'post',
      url,
      headers: {
        'access-token': store.state.token,
        'user-id': store.state.user_id,
        'Content-Type': 'application/json'
      },
      responseType: 'blob', // 表明返回服务器返回的数据类型
      data
    }).then(data => {
      res(data)
    }).catch(err => {
      rej(err)
    })
  })
}


// 封装包含上传内容的方法
// @url:上传地址
// @data:上传数据
function upload(url, data = {}) {
  return new Promise((res, rej) => {
    let form = new FormData();
    for (var key in data) {
      // append:向表单实例添加数据的方法
      // key: 数据的名称
      // value: 数据的值
      form.append(key, data[key]);
    }
    axios({
      method: 'post',
      url,
      headers: {
        'Content-Type': 'multipart/form-data',
        'access-token': store.state.token,
        'user-id': store.state.user_id
      },
      data: form,
    }).then(data => {
      res(data)
    }).catch(err => {
      rej(err)
    })
  })
}



function yaSuoImg(file) {
  let reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = v => {
    console.log(v);
  };
  let canvasWidth = res.width //图片原始长宽
  let canvasHeight = res.height
  if (canvasWidth > canvasHeight) {
    if (canvasWidth > 800) {
      canvasWidth = 800;
      canvasHeight = canvasHeight / (canvasWidth / 800);
    }
  } else if (canvasWidth < canvasHeight) {
    if (canvasHeight > 800) {
      canvasHeight = 800;
      canvasWidth = canvasWidth / (canvasHeight / 800);
    }
  }
  let img = new Image()
  img.src = res.path
  let canvas = document.createElement('canvas');
  let ctx = canvas.getContext('2d')
  canvas.width = canvasWidth
  canvas.height = canvasHeight
  ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight)
  birthimgs = canvas.toDataURL("image/jpeg");
  console.log(birthimgs)
}

// base64转码（压缩完成后的图片为base64编码，这个方法可以将base64编码转回file文件）
function dataURLtoFile(dataurl, name) {
  let arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], name, { type: mime });
}

//将blob转换为file
// function blobToFile(theBlob, fileName) {
//     theBlob.lastModifiedDate = new Date()
//     theBlob.name = fileName;
//     return theBlob;
//   }

//压缩图片
function compressImg(file) {
  var newfile;
  var blob;
  var name = file.name
  var fileSize = parseFloat(parseInt(file['size']) / 1024 / 1024).toFixed(2);
  var read = new FileReader();
  read.readAsDataURL(file);
  return new Promise(function (resolve, reject) {
    read.onload = function (e) {
      var img = new Image();
      img.src = e.target.result;
      img.onload = function () {
        //默认按比例压缩
        var w = this.width,
          h = this.height;
        //生成canvas
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        var base64;
        // 创建属性节点
        canvas.setAttribute("width", w);
        canvas.setAttribute("height", h);
        ctx.drawImage(this, 0, 0, w, h);
        if (fileSize < 1) {
          //如果图片小于一兆 那么不执行压缩操作
          base64 = canvas.toDataURL(file['type'], 0.1);
        } else if (fileSize > 1 && fileSize < 2) {
          //如果图片大于1M并且小于2M 那么压缩0.5
          base64 = canvas.toDataURL(file['type'], 0.1);
        } else {
          //如果图片超过2m 那么压缩0.2
          base64 = canvas.toDataURL(file['type'], 0.1);
        }
        // 回调函数返回file的值（将base64编码转成file）
        newfile = dataURLtoFile(base64, name); //如果后台接收类型为base64的话这一步可以省略
        //   newfile = blobToFile(blob, name)
        resolve(newfile)
      };
    };
  })
};


export default {
  get,
  post,
  upload,
  compressImg,
  yaSuoImg,
  exportPost
}